package com.fishsticks.view;

import java.util.ArrayList;
import java.util.Date;

import com.fishsticks.R;
import com.fishsticks.model.Category;
import com.fishsticks.model.CategoryAdapter;
import com.fishsticks.model.DatabaseManager;
import com.fishsticks.model.FilterDialog;
import com.fishsticks.model.ToDoAdapter;
import com.fishsticks.model.ToDoItem;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ToDoListActivity extends Activity {

	private Menu menu;
	private TextView noToDoItemsText;
	private ListView toDoItemsListView;
	private ToDoAdapter toDoItemsAdapter;
	private DatabaseManager db;
	private String currentUser;
	private Bundle extras;
	private ArrayList<ToDoItem> toDoItems;
	private ArrayList<Category> categories;
	private ArrayList<String> filterOptions, completedOptions;
	private boolean listIsEmpty = false, newMenu = false;
	private AlertDialog.Builder logoutDialog, filterDialog;

	/**
     * Called when the activity is first created.
     * Initializes home screen to-do list page
     * and action bar buttons on top
     */
    /* (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        this.setContentView(R.layout.to_do_list_page);

        // Gets recently created username if coming
        // from the registration page
        extras = getIntent().getExtras();
        toDoItemsListView = (ListView) findViewById(R.id.to_do_items_list);
        
        
        //Sets up the logout and filter dialog boxes
        logoutDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.white_orange_dialog));
        logoutDialog.setTitle("Log out");
    	logoutDialog.setMessage("Are you sure you want to log out?");
    	        
        filterDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.white_orange_dialog));
        filterDialog.setTitle("Filter");
		filterDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
        
        db = new DatabaseManager(this);

        filterOptions = new ArrayList<String>();
        filterOptions.add("Completion");
        filterOptions.add("Category");
        filterOptions.add("Date");
        filterOptions.add("Keyword");
        
        completedOptions = new ArrayList<String>();
        completedOptions.add("Find Complete Items");
        completedOptions.add("Find Incomplete Items");
        
        currentUser = db.getLoggedInUser();
        toDoItems = db.getToDoItems(currentUser);
        categories = db.getCategories(currentUser);

        toDoItemsAdapter = new ToDoAdapter(this, R.layout.to_do_item_row, toDoItems);
        toDoItemsListView.setAdapter(toDoItemsAdapter);

        //refreshes the list if a new to-do was added
        if(extras != null)
        {
        	if(extras.getBoolean("refreshList")) {
        		toDoItemsAdapter.notifyDataSetChanged();

        		if(listIsEmpty) {
        			listIsEmpty = false;
        			toDoItems.remove(0);
        		}
        	}
        }

        //shows "no to do items" text
        // if list of to-do items is empty
        if(toDoItems.size() < 1)
        	listIsEmpty = true;

        if(listIsEmpty) {
        	toDoItems.add(new ToDoItem("You have no to do's!", "Click the plus button to add a new one", null, null, null, false, -1));
        	toDoItemsAdapter.notifyDataSetChanged();
        }

        db.close();
    }



    /**
     * Creates the menu options in the action bar at the top.
     *    
     *  @param menu The Menu item created that is being prepared
     *  @return A boolean representing the status
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	this.menu = menu;
    	
   		getMenuInflater().inflate(R.menu.to_do_page_menu, menu);
   		
    	return true;
    }
    
    
    
    /**
     * Called after the options menu is created; Prepares
     *  the menu items based on the menu layout inputted
     *  
     *  @param menu The Menu item created that is being prepared
     *  @return A boolean representing the status
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	this.menu = menu;

    	if(newMenu) {
    		MenuItem searchButton = menu.findItem(R.id.search_button);
    		MenuItem cancelButton = menu.findItem(R.id.cancel_button);
    		MenuItem addButton = menu.findItem(R.id.add_new_to_do_button);
    		MenuItem manageCategories = menu.findItem(R.id.go_to_categories_button);
    		
    		if(searchButton != null) {
    			searchButton.setVisible(false);
    			searchButton.setEnabled(false);
    		}
    		
    		if(cancelButton != null) {
    			cancelButton.setVisible(true);
    			cancelButton.setEnabled(true);
    		}
    		
    		if(addButton != null) {
    			addButton.setVisible(false);
    			addButton.setEnabled(false);
    		}
    		
    		if(manageCategories != null) {
    			manageCategories.setVisible(false);
    			manageCategories.setEnabled(false);
    		}
    	}
    	
    	//changes action bar icons based on viewing 
    	// entire to-do list or only filtered to-do's
    	else {
    		MenuItem searchButton = menu.findItem(R.id.search_button);
    		MenuItem cancelButton = menu.findItem(R.id.cancel_button);
    		MenuItem addButton = menu.findItem(R.id.add_new_to_do_button);
    		MenuItem manageCategories = menu.findItem(R.id.go_to_categories_button);
    		
    		if(searchButton != null) {
    			searchButton.setVisible(true);
    			searchButton.setEnabled(true);
    		}
    		
    		if(cancelButton != null) {
    			cancelButton.setVisible(false);
    			cancelButton.setEnabled(false);
    		}
    		
    		if(addButton != null) {
    			addButton.setVisible(true);
    			addButton.setEnabled(true);
    		}
    		
    		if(manageCategories != null) {
    			manageCategories.setVisible(true);
    			manageCategories.setEnabled(true);
    		}
    	}
    	
    	return true;
    }




    /**
     * Listeners for the top bar menu items
     * 
     * @param item The MenuItem object 
     * representing what button was pressed
     * @return A boolean representing the status
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	
    	Intent addIntent = new Intent(this, AddNewToDoActivity.class);
    	addIntent.putExtra("username", currentUser);
    	addIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    	Intent categoryIntent = new Intent(this, CategoryListActivity.class);
    	Intent mapIntent = new Intent(this, MapsActivity.class);
    	mapIntent.putExtra("showToDoList", true);
    	mapIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    	switch(item.getItemId())
        {
        	//When the user clicks the top-left arrow icon
            case android.R.id.home:
            	setupLogoutDialog();
            	return true;
    	
            	
            	
            //skips to new to-do item page when plus button clicked
            case R.id.add_new_to_do_button:
            	startActivityForResult(addIntent, R.string.to_do_activity_request_code);
            	return true;
            	
            	
            	
            //skips to map page when maps menu-item is clicked
            case R.id.go_to_map_button:
            	startActivity(mapIntent);
            	return true;
      	
            	
            	
            //opens categories page
            case R.id.go_to_categories_button:
            	startActivity(categoryIntent);
            	return true;
        	
            	
            //Doesnt do anything except open a sub-menu with 
            //    the 4 different search terms (below)
            case R.id.search_button:
            	return true;

            	
            //Brings up 'filter by category' dialog window
            case R.id.submenu_category_search: 	
            	Context mContext = getBaseContext();
            	LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            	View categoryFilterDialogView = inflater.inflate(R.layout.filter_category_dialog, (ViewGroup)findViewById(R.id.filter_category_dialog_box_root));
            	
            	//Adds the categories to the selector in the dialog box
            	final Spinner categoriesSpinner = (Spinner) categoryFilterDialogView.findViewById(R.id.categorySpinnerCategoryPage);
            	CategoryAdapter categoriesAdapter = new CategoryAdapter(getBaseContext(), R.layout.completion_filter_item_row, categories);
            	categoriesSpinner.setAdapter(categoriesAdapter);
            	
            	filterDialog.setPositiveButton("Filter", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface dialog, int which) {
        				//clears the current to-do list
        				toDoItemsAdapter.clear();
        				toDoItemsAdapter.notifyDataSetChanged();
        				
        				//gets the category-specific to-do's
        				toDoItems = db.getToDoItemsWithCategory(currentUser, new Category(categoriesSpinner.getSelectedItem().toString()));
        				//if theres no results
        				if(toDoItems.size() < 1)
        					toDoItems.add(new ToDoItem("No results", "", null, null, null, false, -1));

        				//Create new adapter to bind data elements to list view
        				ToDoAdapter newAdapter = new ToDoAdapter(ToDoListActivity.this, R.layout.to_do_item_row, toDoItems);
        				toDoItemsListView.setAdapter(newAdapter);
        				newAdapter.notifyDataSetChanged();
        				
        				//Lets the onPrepareOptionsMenu method know to 
        				// re-draw the menu bar with a cancel button
        				newMenu = true;
        				onPrepareOptionsMenu(menu);
                    	Toast.makeText(getBaseContext(), "Press the X to go back to your to-do list", Toast.LENGTH_SHORT).show();
        			}
        		});
            	
            	//Shows the dialog box
            	filterDialog.setView(categoryFilterDialogView);
            	filterDialog.show();
            	return true;
            	
            	
            	
            //Brings up 'filter by completion' dialog window
            case R.id.submenu_completion_search: 	
            	Context mContext2 = getBaseContext();
            	LayoutInflater inflater2 = (LayoutInflater) mContext2.getSystemService(LAYOUT_INFLATER_SERVICE);
            	View completionFilterDialogView = inflater2.inflate(R.layout.filter_completion_dialog, (ViewGroup)findViewById(R.id.completion_dialog_box_root));
            	
            	//Gets the check box in the dialog
            	final Spinner completedSpinner = (Spinner) completionFilterDialogView.findViewById(R.id.completedSpinnerCompletionPage);
            	ArrayAdapter<String> completionAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.completion_filter_item_row, completedOptions);
            	completedSpinner.setAdapter(completionAdapter);
            	
            	filterDialog.setPositiveButton("Filter", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface dialog, int which) {
        				//clears the current to-do list
        				toDoItemsAdapter.clear();
        				toDoItemsAdapter.notifyDataSetChanged();
        				
        				String selection = completedSpinner.getSelectedItem().toString();
        				
        				//gets the completion-specific to-do's
        				if(selection.equals(completedOptions.get(0)))
        					toDoItems = db.getCompletedItems(currentUser);
        				else
        					toDoItems = db.getIncompleteItems(currentUser);
        				
        				//if theres no results
        				if(toDoItems.size() < 1)
        					toDoItems.add(new ToDoItem("No results", "", null, null, null, false, -1));
        				
        				//Create new adapter to bind data elements to list view
        				ToDoAdapter newAdapter = new ToDoAdapter(ToDoListActivity.this, R.layout.to_do_item_row, toDoItems);
        				toDoItemsListView.setAdapter(newAdapter);
        				newAdapter.notifyDataSetChanged();
        				
        				//Lets the onPrepareOptionsMenu method know to 
        				// re-draw the menu bar with a cancel button
        				newMenu = true;
        				onPrepareOptionsMenu(menu);
                    	Toast.makeText(getBaseContext(), "Press the X to go back to your to-do list", Toast.LENGTH_SHORT).show();
        			}
        		});
            	
            	//Shows the dialog box
            	filterDialog.setView(completionFilterDialogView);
            	filterDialog.show();
            	Toast.makeText(this, "Press the X to go back to your to-do list", Toast.LENGTH_SHORT).show();
            	return true;
            
            	
            	
            //Brings up 'filter by date' dialog window
            case R.id.submenu_date_search: 	
            	Context mContext3 = getBaseContext();
            	LayoutInflater inflater3 = (LayoutInflater) mContext3.getSystemService(LAYOUT_INFLATER_SERVICE);
            	View dateFilterDialogView = inflater3.inflate(R.layout.filter_date_dialog, (ViewGroup)findViewById(R.id.date_dialog_box_root));
            	
            	//Gets the check box in the dialog
            	final DatePicker datePicker = (DatePicker) dateFilterDialogView.findViewById(R.id.datePickerDatePage);
            	
            	filterDialog.setPositiveButton("Filter", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface dialog, int which) {
        				//clears the current to-do list
        				toDoItemsAdapter.clear();
        				toDoItemsAdapter.notifyDataSetChanged();
        				
        				//gets the completion-specific to-do's
        				toDoItems = db.getToDoItemsAfterDate(currentUser, new Date(datePicker.getYear(), datePicker.getMonth()+1, datePicker.getDayOfMonth()));
        				
        				//if theres no results
        				if(toDoItems.size() < 1)
        					toDoItems.add(new ToDoItem("No results", "", null, null, null, false, -1));
        				
        				//Create new adapter to bind data elements to list view
        				ToDoAdapter newAdapter = new ToDoAdapter(ToDoListActivity.this, R.layout.to_do_item_row, toDoItems);
        				toDoItemsListView.setAdapter(newAdapter);
        				newAdapter.notifyDataSetChanged();
        				
        				//Lets the onPrepareOptionsMenu method know to 
        				// re-draw the menu bar with a cancel button
        				newMenu = true;
        				onPrepareOptionsMenu(menu);
                    	Toast.makeText(getBaseContext(), "Press the X to go back to your to-do list", Toast.LENGTH_SHORT).show();
        			}
        		});
            	
            	//Shows the dialog box
            	filterDialog.setView(dateFilterDialogView);
            	filterDialog.show();
            	return true;
            	
            	
            	
            //Brings up 'filter by keyword' dialog window
            case R.id.submenu_keyword_search: 	
            	Context mContext4 = getBaseContext();
            	LayoutInflater inflater4 = (LayoutInflater) mContext4.getSystemService(LAYOUT_INFLATER_SERVICE);
            	View keywordFilterDialogView = inflater4.inflate(R.layout.filter_keyword_dialog, (ViewGroup)findViewById(R.id.filter_keyword_dialog_box_root));
            	
            	//Gets the check box in the dialog
            	final EditText keyword = (EditText) keywordFilterDialogView.findViewById(R.id.keywordFilterText);
            	
            	filterDialog.setPositiveButton("Filter", new DialogInterface.OnClickListener() {
        			@Override
        			public void onClick(DialogInterface dialog, int which) {
        				//clears the current to-do list
        				toDoItemsAdapter.clear();
        				toDoItemsAdapter.notifyDataSetChanged();
        				
        				//gets the completion-specific to-do's
        				toDoItems = db.searchToDoList(currentUser, keyword.getText().toString());
        				
        				//if theres no results
        				if(toDoItems.size() < 1)
        					toDoItems.add(new ToDoItem("No results", "", null, null, null, false, -1));
        				
        				//Create new adapter to bind data elements to list view
        				ToDoAdapter newAdapter = new ToDoAdapter(ToDoListActivity.this, R.layout.to_do_item_row, toDoItems);
        				toDoItemsListView.setAdapter(newAdapter);
        				newAdapter.notifyDataSetChanged();
        				
        				//Lets the onPrepareOptionsMenu method know to 
        				// re-draw the menu bar with a cancel button
        				newMenu = true;
        				onPrepareOptionsMenu(menu);
                    	Toast.makeText(getBaseContext(), "Press the X to go back to your to-do list", Toast.LENGTH_SHORT).show();
        			}
        		});
            	
            	//Shows the dialog box
            	filterDialog.setView(keywordFilterDialogView);
            	filterDialog.show();
            	return true;
            	
            	
            	
            //Returns to entire to-do list from filtered items 
            //     and re-draws the top menu bar icons
            case R.id.cancel_button:
            	toDoItems = db.getToDoItems(currentUser);
            	toDoItemsAdapter = new ToDoAdapter(this, R.layout.to_do_item_row, toDoItems);
                toDoItemsListView.setAdapter(toDoItemsAdapter);
                toDoItemsAdapter.notifyDataSetChanged();
                db.close();
                
                //Lets the onPrepareOptionsMenu method know to 
				// re-draw the menu bar without the cancel button
				newMenu = false;
				onPrepareOptionsMenu(menu);
                
            	return true;
            	
            	
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    
    
    /**
     * Shows logout dialog when back button 
     * is pressed on main to do list screen
     * 
     * @param keyCode The keycode corresponding to the button pressed
     * @param event The KeyEvent created by pressing this button
     * @return A boolean respresenting the status
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setupLogoutDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    



    /**
     * System method called when you return back 
     *   to this activity from a previous one
     *   
     * @param requestCode The int code requested
     * @param resultCode The result int code that specifies the response
     * @param data The intent passed from the other activity
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(resultCode == R.string.add_to_do_successful_code &&
    	   resultCode == R.string.to_do_activity_request_code) {
    		if(data.hasExtra("username")) {
    			currentUser = data.getExtras().getString("username");
    			//Toast.makeText(this, "intent user: " + data.getExtras().getString("username"), Toast.LENGTH_SHORT).show();
    		}
    		else {
    			currentUser = new DatabaseManager(this).getLoggedInUser();
    			Toast.makeText(this, "DB user: " + currentUser, Toast.LENGTH_SHORT).show();
    		}
    	}
    }
    
    
    
    /**
     * Sets up the log out pop-up dialog box when
     *  you press the home button or back button
     */
    public void setupLogoutDialog() {
    	final Intent logoutIntent = new Intent(this, LoginActivity.class);
    	logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	
    	logoutDialog.setPositiveButton("Yes", new Dialog.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
                startActivity(logoutIntent);
                finish();
		    }
		});
    	logoutDialog.setNegativeButton("No", new Dialog.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
		    }
		});
    	logoutDialog.show();
    }

}


